import fs from 'fs'
import path from 'path'
import { CRX_OUTDIR, CRX_CONTENT_OUTDIR, CRX_BACKGROUND_OUTDIR } from './globalConfig.js'

// 拷贝目录文件
const copyDirectory = (src, dest) => {
  const exists = fs.existsSync(dest)
  if (!exists) {
    fs.rmdirSync(dest)
  }

  fs.readdirSync(src).forEach((file) => {
    const srcPath = path.join(src, file)
    const destPath = path.join(dest, file)

    if (fs.lstatSync(srcPath).isDirectory()) {
      copyDirectory(srcPath, destPath)
    } else {
      fs.copyFileSync(srcPath, destPath)
    }
  })
}

// 删除目录及文件
const deleteDirectory = (dir) => {
  const exists = fs.existsSync(dir)

  if (exists) {
    fs.readdirSync(dir).forEach(
      (file) => {
        const srcPath = path.join(dir, file)
        if (fs.lstatSync(srcPath).isDirectory()) {
          deleteDirectory(srcPath)
        } else {
          fs.unlinkSync(srcPath)
        }
      }
    )
    fs.rmdirSync(dir)
  }
}

const contentOutDir = path.resolve(process.cwd(), CRX_CONTENT_OUTDIR)
const backgroundOutDir = path.resolve(process.cwd(), CRX_BACKGROUND_OUTDIR)
const outDir = path.resolve(process.cwd(), CRX_OUTDIR)
// 复制源目录至目标目录中
copyDirectory(contentOutDir, outDir)
copyDirectory(backgroundOutDir, outDir)
// 删除源目录
deleteDirectory(contentOutDir)
deleteDirectory(backgroundOutDir)